
import UIKit
import BUAdSDK
//import GoogleMobileAds

extension Notification.Name {
    static let ShowFullScrrenAD = Notification.Name.init(rawValue: "ShowFullScrrenAD")
    static let SDKInitFinish = Notification.Name.init(rawValue: "SDKInitFinish")
}

struct TestAd {
    //开屏
    static let Google_Open_AD = "ca-app-pub-3940256099942544/5662855259"
    //横幅
    static let Google_Banner_AD = "ca-app-pub-3940256099942544/2934735716"
    //插页
    static let Google_Interstitial_AD = "ca-app-pub-3940256099942544/4411468910"
    //激励视频
    static let Google_Video_AD = "ca-app-pub-3940256099942544/1712485313"
}

class ADManager: NSObject {
    
    static var initFinish = false
    
    /***穿山甲相关配置***/
    static let BUAdAppID = "5524047"
    //开屏
    let BUAdKPID = "889147608"
    //Banner
    let BUAdBannerID = "957111883"


    /***Google相关配置***/
    static let GoogleAppID  = "ca-app-pub-4579422483792864~4307908186"
    //Google Banner
    let GBannerID = "ca-app-pub-4579422483792864/7376661320"
    //Google开屏
    let GKPID = "ca-app-pub-4579422483792864/9807646873"
    //Google插屏
    let GCPID = TestAd.Google_Interstitial_AD
    //Google 激励视频
    let GVideoID = TestAd.Google_Video_AD
    
    var showStart: ((Int) -> Void)?
    
    @objc var showFinish:((Int) -> Void)?
    
    var showUnFinish:(() -> Void)?
    
    var showFailed:(() -> Void)?
    
    var adClose:(() -> Void)?
    
    /**穿山甲**/
    //开屏
    var splashView: BUSplashAd?
    //banner
    var bannerView: BUNativeExpressBannerView?
    //新插屏
    var fullscreenVideoAd: BUNativeExpressFullscreenVideoAd?
    
    /**Google**/
//    //banner
//    var GAD_bannerView: GADBannerView?
//    //插屏
//    var GAD_fullscreenAd: GADInterstitialAd?
//    //激励视频
//    var GAD_videoAd: GADRewardedAd?
    
    @objc static let BannerSize: CGFloat = 70
    
    
    var currentTag = 0
    weak var currentVC: UIViewController!
            
   static var isFisrtEnter: Bool {
        get {
            if UserDefaults.standard.object(forKey: "isFirstEnter") != nil {
                return false
            }
            return true
        }
        set {
            UserDefaults.standard.set("1", forKey: "isFirstEnter")
            UserDefaults.standard.synchronize()
        }
    }
    
    //MARK: 开屏
    func loadKP() {
        if AppProducts.shared.isPurchased {
            return
        }
        closeSplashView()
        splashView = BUSplashAd(slotID: BUAdKPID, adSize: CGSize(width: CGFloat.screenWidth, height: CGFloat.screenHeight))
        splashView?.delegate = self
        splashView?.loadData()
    }
    
    func closeSplashView() {
        if splashView != nil {
            splashView?.removeSplashView()
            splashView = nil
        }
    }
        
    //MARK: 激励视频
    //用于区分哪个界面
    @objc func loadAdVideo(currentVC:UIViewController) {
//        currentTag = tag
//        self.currentVC = currentVC
//        currentVC.showHUD()
//        if AppConfig.isZh {
//            let model = BURewardedVideoModel()
//            model.userId = "123"
//            videoAd = BUNativeExpressRewardedVideoAd(slotID: BUAdVideoID, rewardedVideoModel: model)
//            videoAd?.delegate = self
//            videoAd?.loadData()
//        }else{
//            GADRewardedAd.load(withAdUnitID: GVideoID, request: GADRequest()) {[weak self] ad, err in
//                guard let self = self else {
//                    return
//                }
//                if err != nil {
//                    currentVC.dismissHUD()
//                    print("Google 激励视频 error", err?.localizedDescription as Any)
//                    currentVC.showHUDTextOnly(NSLocalizedString("网络异常，请稍微重试", comment: ""))
//                    return
//                }
//                self.GAD_videoAd = ad
//                self.GAD_videoAd?.fullScreenContentDelegate = self
//                self.GAD_videoAd?.present(fromRootViewController: currentVC, userDidEarnRewardHandler: {
//                    ADUtils.shared.updateAdTimes()
//                    self.showFinish?(self.currentTag)
//                    print("视频观看完成")
//                })
//            }
//        }

    }

    
    //MARK: Banner广告
    @objc func loadBanner(currentVC: UIViewController, isMainVC: Bool) {
        if AppProducts.shared.isPurchased {
            return
        }
        if let temp = currentVC.view.viewWithTag(300) {
            temp.removeFromSuperview()
        }
        self.currentVC = currentVC
        let bottom: CGFloat = isMainVC ? (CGFloat.navHeight + CGFloat.bottomPadding) : CGFloat.bottomPadding 
        let bannerSize = CGSize(width: CGFloat.screenWidth, height: ADManager.BannerSize)
        if !AppConfig.isEnglishEnv {
            bannerView = BUNativeExpressBannerView(slotID: BUAdBannerID, rootViewController: currentVC, adSize: bannerSize, interval: 30)
            bannerView?.frame = CGRect(x: 0, y: CGFloat.screenHeight-bannerSize.height-bottom, width: bannerSize.width, height: bannerSize.height)
            bannerView?.delegate = self
            bannerView?.tag = 300
            bannerView?.loadAdData()
        }else{
//            GAD_bannerView = GADBannerView(adSize: GADAdSizeFromCGSize(bannerSize))
//            GAD_bannerView?.frame = CGRect(x: 0, y: CGFloat.screenHeight-bannerSize.height-bottom, width: bannerSize.width, height: bannerSize.height)
//            GAD_bannerView?.adUnitID = GBannerID
//            GAD_bannerView?.rootViewController = currentVC
//            GAD_bannerView?.delegate = self
//            GAD_bannerView?.load(GADRequest())
        }
    }
    
    @objc func removeBannerView() {
        if !AppConfig.isEnglishEnv {
            if bannerView == nil {
                return
            }
            bannerView?.removeFromSuperview()
        }else{
//            if GAD_bannerView == nil {
//                return
//            }
//            GAD_bannerView?.removeFromSuperview()
        }

    }
 
    //MARK: 插屏
    @objc func loadChaPin(currentVC: UIViewController) {
        if AppProducts.shared.isPurchased {
            return
        }
        self.currentVC = currentVC
        if !AppConfig.isEnglishEnv  {
//            fullscreenVideoAd = BUNativeExpressFullscreenVideoAd(slotID: BUAdCPID)
//            fullscreenVideoAd?.delegate = self
//            fullscreenVideoAd?.loadData()
        }else{
//            GADInterstitialAd.load(withAdUnitID: GCPID, request: GADRequest()) {[weak self] ad, err in
//                if err != nil {
//                    print("Google 插屏 error", err?.localizedDescription as Any)
//                    return
//                }
//                self?.GAD_fullscreenAd = ad
//                self?.GAD_fullscreenAd?.fullScreenContentDelegate = self
//                self?.GAD_fullscreenAd?.present(fromRootViewController: currentVC)
//            }
        }

    }
    
    ///获取当前控制器
     func getAppCurrentVC() ->UIViewController? {
         guard let vc = UIApplication.shared.windows.first(where: {$0.isKeyWindow})?.rootViewController else {
             return nil
         }
        
         if (vc.isKind(of: UITabBarController.self)) {
            return ((vc as! UITabBarController).selectedViewController as! UINavigationController).visibleViewController
         }else if (vc.isKind(of: UINavigationController.self)){
            return (vc as! UINavigationController).visibleViewController
         }else if ((vc.presentedViewController) != nil){
            return  vc.presentedViewController
         }
        
         return vc
    }
    
    
}


//MARK: BUSplashAdDelegate
extension ADManager: BUSplashAdDelegate {
    func splashAdDidClick(_ splashAd: BUSplashAd) {
        closeSplashView()
    }
    
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        closeSplashView()
    }
    
    
    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        if let rootVC = UIApplication.shared.windows.first?.rootViewController {
            splashAd.showSplashView(inRootViewController: rootVC)
        }
    }
    
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("开屏加载失败", error?.errorCode ?? "", error?.localizedFailureReason ?? "")
        closeSplashView()
    }
    
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("开屏渲染失败", error?.localizedDescription ?? "")
    }
    
    func splashAdWillShow(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdDidShow(_ splashAd: BUSplashAd) {
        
    }
    
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {
        closeSplashView()
    }
    
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {
        
    }
    
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: Error?) {
        
    }
    
}


//MARK: BUNativeExpressBannerViewDelegate
extension ADManager: BUNativeExpressBannerViewDelegate {
    func nativeExpressBannerAdViewDidLoad(_ bannerAdView: BUNativeExpressBannerView) {
        print("banner加载成功")
        
    }
    
    func nativeExpressBannerAdViewRenderSuccess(_ bannerAdView: BUNativeExpressBannerView) {
        showStart?(currentTag)
        currentVC.view.addSubview(bannerAdView)
    }
    
    func nativeExpressBannerAdViewDidClick(_ bannerAdView: BUNativeExpressBannerView) {
        print("banner点击")
//        adClose?()
    }
    
    func nativeExpressBannerAdViewRenderFail(_ bannerAdView: BUNativeExpressBannerView, error: Error?) {
        print("banne渲染失败 error = \(error?.localizedDescription ?? "")")
        bannerView?.removeFromSuperview()
    }
    
    func nativeExpressBannerAdView(_ bannerAdView: BUNativeExpressBannerView, didLoadFailWithError error: Error?) {
        print("banner加载失败 error = \(error?.localizedDescription as Any)")
    }
    
    func nativeExpressBannerAdViewDidCloseOtherController(_ bannerAdView: BUNativeExpressBannerView, interactionType: BUInteractionType) {
        adClose?()
        bannerView?.removeFromSuperview()
    }
    
    func nativeExpressBannerAdViewDidRemoved(_ bannerAdView: BUNativeExpressBannerView) {
        adClose?()
        bannerView?.removeFromSuperview()
    }
}

//MARK: BUNativeExpresInterstitialAdDelegate
extension ADManager: BUNativeExpressFullscreenVideoAdDelegate {
    func nativeExpressFullscreenVideoAdDidLoad(_ fullscreenVideoAd: BUNativeExpressFullscreenVideoAd) {
     
    }
    
    func nativeExpressFullscreenVideoAdDidDownLoadVideo(_ fullscreenVideoAd: BUNativeExpressFullscreenVideoAd) {
        print("插屏下载成功")
        showStart?(currentTag)
        if self.fullscreenVideoAd != nil {
            self.fullscreenVideoAd?.show(fromRootViewController: self.currentVC)
        }
    }
    
    //渲染成功
    func nativeExpressRewardedVideoAdViewRenderSuccess(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd) {
      print("插屏渲染成功")
    }
    
    func nativeExpressFullscreenVideoAdViewRenderFail(_ rewardedVideoAd: BUNativeExpressFullscreenVideoAd, error: Error?) {
        print("新插屏渲染失败 = \(error.debugDescription)")
    }
    
    func nativeExpressRewardedVideoAd(_ rewardedVideoAd: BUNativeExpressRewardedVideoAd, didFailWithError error: Error?) {
        
    }
    
    func nativeExpressFullscreenVideoAdDidClick(_ fullscreenVideoAd: BUNativeExpressFullscreenVideoAd) {
        showFinish?(currentTag)
    }
    
    func nativeExpressFullscreenVideoAdDidClose(_ fullscreenVideoAd: BUNativeExpressFullscreenVideoAd) {
        showFinish?(currentTag)
    }
}

/*
//MARK: Google Ad
extension ADManager {
    func requestGoogleAppOpenAd(result:((GADAppOpenAd) -> Void)?) {
        GADAppOpenAd.load(withAdUnitID: GKPID, request: GADRequest(), orientation: .portrait) { ad, err in
            if err != nil {
                print("Google Ad open error", err?.localizedDescription as Any)
                return
            }
            if let tempAd = ad {
                result?(tempAd)
            }
        }
    }
    
    func requestBuAppOpenAd(result:(() -> Void)?) {
        
    }
}

extension ADManager: GADBannerViewDelegate {
    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
      print("bannerViewDidReceiveAd")
        showStart?(currentTag)
        currentVC.view.addSubview(bannerView)
    }

    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
      print("bannerView:didFailToReceiveAdWithError: \(error.localizedDescription)")
        bannerView.removeFromSuperview()
    }

    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
      print("bannerViewDidRecordImpression")
    }

    func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
      print("bannerViewWillPresentScreen")
    }

    func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
      print("bannerViewWillDIsmissScreen")
    }

    func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
      print("bannerViewDidDismissScreen")
        adClose?()
        bannerView.removeFromSuperview()
    }
}

extension ADManager: GADFullScreenContentDelegate {
    /// Tells the delegate that the ad failed to present full screen content.
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("Ad did fail to present full screen content.")
        currentVC.dismissHUD()
        showFinish?(currentTag)
    }

    /// Tells the delegate that the ad will present full screen content.
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("Ad will present full screen content.")
        showStart?(currentTag)
        currentVC.dismissHUD()
    }
    
    func adDidRecordClick(_ ad: GADFullScreenPresentingAd) {
        showFinish?(currentTag)
    }

    /// Tells the delegate that the ad dismissed full screen content.
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
      print("Ad did dismiss full screen content.")
        showFinish?(currentTag)
    }
}
*/
